package com.sunstar.liveplugin.view.live

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import com.netease.LSMediaCapture.lsMediaCapture
import com.netease.LSMediaCapture.lsMessageHandler
import com.netease.vcloud.video.effect.VideoEffect
import com.netease.vcloud.video.render.NeteaseView
import com.sunstar.liveplugin.util.FaceUUtil
import com.sunstar.liveplugin.util.LiveInstance
import io.flutter.plugin.common.*
import io.flutter.plugin.platform.PlatformView
import java.security.MessageDigest
import kotlin.experimental.and

class VideoView(private val registrar: PluginRegistry.Registrar, id: Int, val activity: Activity?, val messager: BinaryMessenger) : PlatformView, MethodChannel.MethodCallHandler {
    var videoView: NeteaseView? = null
    private val channel: MethodChannel
    private var event: EventChannel.EventSink? = null
    var hanlder = lsMessageHandler { i, any ->
        event?.success(mapOf("type" to i, "info" to CodeUtil.getInfoByUtil(i)))
    }

    init {
        addLifeCycle()
        channel = MethodChannel(messager, "com.sunstar.liveplugin.viewControl")
        channel.setMethodCallHandler(this)
        activity?.run {
            LiveInstance.Instance.initLiveConfig(application.applicationContext, hanlder)
        }
        EventChannel(messager, "com.sunstar.liveplugin.viewControl_event").setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                event = events
            }

            override fun onCancel(arguments: Any?) {
                event = null
            }
        })
    }

    private fun addLifeCycle() {
        activity?.application?.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(p0: Activity?) {

            }

            override fun onActivityResumed(p0: Activity?) {
            }

            override fun onActivityStarted(p0: Activity?) {
            }

            override fun onActivityDestroyed(p0: Activity?) {
                LiveInstance.Instance.onDestroy()
            }

            override fun onActivitySaveInstanceState(p0: Activity?, p1: Bundle?) {
            }

            override fun onActivityStopped(p0: Activity?) {
            }

            override fun onActivityCreated(p0: Activity?, p1: Bundle?) {
            }
        })
    }

    override fun getView(): View = initVideoView()

    private fun initVideoView(): View {
        if (videoView == null) {
            videoView = NeteaseView(activity)
        }
        return videoView!!
    }

    override fun dispose() {
        event = null
        videoView = null
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "preView" -> {
                activity?.window?.run {
                    addFlags(WindowManager.LayoutParams.FLAG_SECURE)
                    addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
                }

                videoView?.run {
                    LiveInstance.Instance.initVideoStreamingPara(lsMediaCapture.StreamType.AV).videoPreview(this, call.argument<Boolean>("isFaceU")!!)
                }
            }
            "destroy" -> {
                LiveInstance.Instance.onDestroy()
                activity?.window?.run {
                    clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
                    clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
                }
            }
            "switchCamera" -> {
                LiveInstance.Instance.switchCamera()
            }
            "changeFilter" -> {
                var type: VideoEffect.FilterType? = null
                when (call.argument<String>("filterType")!!.toString()) {
                    "FilterType.none" -> type = VideoEffect.FilterType.none
                    "FilterType.clean" -> type = VideoEffect.FilterType.clean
                    "FilterType.fairytale" -> type = VideoEffect.FilterType.fairytale
                    "FilterType.nature" -> type = VideoEffect.FilterType.nature
                    "FilterType.healthy" -> type = VideoEffect.FilterType.healthy
                    "FilterType.tender" -> type = VideoEffect.FilterType.tender
                    "FilterType.whiten" -> type = VideoEffect.FilterType.whiten
                }
                type?.run {
                    LiveInstance.Instance.changeFilter(this)
                }
            }
            "changeFilterLevel" -> {
                LiveInstance.Instance.changeFilterLevel(call.argument<Double>("level")!!)
            }
            "changeOrigation" -> {
                LiveInstance.Instance.changeOrigation()
            }
            "changeBeautyLevel" -> {
                LiveInstance.Instance.changeBeautyLevel(call.argument<Double>("level")!!)
            }
            "addWaterMarker" -> {
                activity?.run {
                    LiveInstance.Instance.addWorkMarker(activity.applicationContext, call.argument<Int>("x")!!, call.argument<Int>("y")!!)
                }
            }
            "changeScreenOrientation" -> {
                LiveInstance.Instance.changeScreenConfig()
            }
            "startPlayMusic" -> {
                LiveInstance.Instance.startPlayMusic(call.argument<String>("urlPath")!!, call.argument<Boolean>("isLoop")!!)
            }
            "startPushStreaming" -> {
                activity?.run {
                    LiveInstance.Instance.startPush(activity.applicationContext, call.argument<String>("pushUrl")!!)
                }
            }
            "pauseLiveStream" -> {
                activity?.run {
                    LiveInstance.Instance.pausePush();
                }
            }
            "rePushLiveStream" -> {
                activity?.run {
                    LiveInstance.Instance.repush();
                }
            }
            "faceUInitComplete" -> {
                result.success(FaceUUtil.instance.isInit())
            }

            "initBeauty" -> {
                LiveInstance.Instance.initWhite(
                        whiteColorPercent = call.argument("whiteColor")!!,
                        redColorPercent = call.argument("redColor")!!,
                        blurPercent = call.argument("blur")!!,
                        filterName = call.argument("filterName")!!,
                        filterPercent = call.argument("filterValue")!!
                )
            }
        }
    }

    private fun digestResult(digest: ByteArray) =
            ((digest[0] and 0xff.toByte()) as Int shl 24) + ((digest[1] and 0xff.toByte()) as Int shl 16) + ((digest[2] and 0xff.toByte()) as Int shl 8) + ((digest[3] and 0xff.toByte()) as Int shl 0)
}